import React, { PropsWithChildren, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { createIntl, createIntlCache, RawIntlProvider } from 'react-intl';
import flatten from 'flat';
import { enUS } from '@/locales/enUS';
import { zhCN } from '@/locales/zhCN';
import { storageService } from '@/common/storageService';
import { usePreviousValue } from '@/hooks';

export let intl;

interface IntlProps {
    onLangChange?: (dispatch, lang) => void;
}

export function Intl(props: PropsWithChildren<IntlProps>) {
    const dispatch = useDispatch();
    const {
        lang,
    } = useSelector((state: any) => {
        return state.config;
    });
    const prevLang = usePreviousValue(lang);
    const storage = storageService.getStorage();
    const locale = storage.lang || lang;
    const messages = getIntlLocaleMessages(locale);
    const cache = createIntlCache();

    intl = createIntl({
        locale,
        messages
    }, cache);

    useEffect(() => {
        if (prevLang && (prevLang !== lang) && props.onLangChange) {
            props.onLangChange(dispatch, lang);
        }

    }, [lang, prevLang, props.onLangChange]);

    return (
        <RawIntlProvider key={locale} value={intl}>
            {props.children}
        </RawIntlProvider>
    );
}

function getIntlLocaleMessages(locale) {
    let messages;

    if (locale.startsWith('en')) {
        messages = enUS;
    } else {
        messages = zhCN;
    }

    return flatten(messages);
}

export function getText(pathStr): string {
    return intl.formatMessage({ id: pathStr });
}
